package threadcoreknowledge.threadobjectclasscommonmethods;

/**
 * 描述：     3个线程，线程1和线程2首先被阻塞，线程3唤醒它们。notify, notifyAll。 start先执行不代表线程先启动。
 *     如果只有两个先
 */
public class WaitNotifyAll implements Runnable {

    private static final Object lock = new Object();


    public static void main(String[] args) throws InterruptedException {
        Runnable r = new WaitNotifyAll();
        Thread threadA = new Thread(r, "线程A");
        Thread threadB = new Thread(r, "线程B");
        Thread threadC = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    lock.notifyAll(); // notifyAll会把锁对象上所有的wait线程都唤醒
                    System.out.println("线程C调用了锁的notifyAll方法");

//                    lock.notify(); // notifyAll 只会锁对象上所有的wait线程都唤醒
//                    System.out.println("线程C调用了锁的notify方法");
                }
            }
        }, "线程C");
        threadA.start();
        threadB.start();
        Thread.sleep(1);
        threadC.start();
    }

    @Override
    public void run() {
        synchronized (lock) {
            System.out.println(Thread.currentThread().getName() + "获取了锁对象");
            try {
                System.out.println(Thread.currentThread().getName() + "锁的wait方法---前");
                lock.wait();
                System.out.println(Thread.currentThread().getName() + "锁的wait方法---后");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
